package com.alinks.modbus.device;

import com.alinks.modbus.slave.codec.TcpMessageCodec;
import com.alinks.modbus.slave.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class AlinksSlaveTest {
    public static void main(String[] args) {
        new AlinksSlaveTest().run();
    }

    public void run() {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(loggingHandler);
                    ch.pipeline().addLast(new TcpMessageCodec());
                    ch.pipeline().addLast(new TcpMessageHandler());
//                    ch.pipeline().addLast(new ASCIIMessageCodec());
//                    ch.pipeline().addLast(new ASCIIMessageHandler());
//                    ch.pipeline().addLast(new RtuMessageCodec());
//                    ch.pipeline().addLast(new RtuMessageHandler());
                }
            });
            Channel channel = bootstrap.bind(502).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
